package com.mc.fastkit

import com.mc.fastkit.ext.andThen
import com.mc.fastkit.ext.dispatch
import com.mc.fastkit.ext.or
import org.junit.Test
import kotlin.random.Random

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    @Test
    fun resultExtTest() {
        generateRandom()
            .andThen { a(it ?: 0) }
            .andThen { b(it.toString()) }
            .onSuccess { println("结果 = $it") }
            .onFailure { System.err.println(it.message) }
    }

    @Test
    fun resultExtTest2() {
        generateRandom()
            .dispatch {
                val a = c(it ?: 0, 10)
                val b = c(it ?: 0, 100)
                a + b
            }.andThen { b(it.toString()) }
            .onSuccess { println("结果 = $it") }
            .onFailure { System.err.println(it.message) }
    }

    @Test
    fun resultExtTest3() {
        generateRandom()
            .andThen { a(it ?: 0) }
            .or {
                println("重新生成随机数")
                a(generateRandom().getOrNull() ?: 0)
            }
            .or {
                println("再次生成随机数")
                a(generateRandom().getOrNull() ?: 0)
            }
            .andThen { b(it.toString()) }
            .onSuccess { println("结果 = $it") }
            .onFailure { System.err.println(it.message) }
    }

    fun generateRandom(): Result<Int> {
        return runCatching { Random.nextInt(0, 10) }
    }

    fun a(value: Int): Result<Int> {
        println("a的参数为$value")
        return if (value > 5) {
            Result.success(value)
        } else {
            Result.failure(Error("结果未达预期"))
        }
    }

    fun b(value: String?): Result<String?> {
        println("b的参数$value")
        return if (value.isNullOrEmpty()) {
            Result.failure(Error("params is null"))
        } else {
            Result.success("success")
        }
    }

    fun c(value: Int, ratio: Int): Int {
        return value * ratio
    }
}